from datetime import date
from typing import Union, List, Optional

from fastapi import APIRouter
from pydantic import BaseModel, Field, field_validator, ValidationInfo


class Addr(BaseModel):
    province: str
    city: str


class User(BaseModel):
    # 1. 给 name 字段添加类型注解（str）
    name: str = 'root'
    age: int = Field(default=0, lt=100, gt=0)  #可以限定大小
    birth: Optional[date] = None # 可为空或日期类
    friends: List[int] = [] # 有默认值可为空,如有值需为int元素
    description: Union[str, None] = None
    addr: Union[Addr, None] = None  # 类型嵌套

    @classmethod
    @field_validator('name')
    # 2. 给验证器参数添加类型注解，推荐抛出 ValueError 而非 assert
    def name_must_alpha(cls, v: str, info: ValidationInfo) -> str:
        if not v.isalpha():
            raise ValueError('name must be alpha (only letters)')
        return v


class Data(BaseModel):
    users: List[User]


postDemo = APIRouter()


@postDemo.post("/user/")
async def create_data(user: User):
    print(user)
    print("*****************")
    print(type(user))
    print("*****************")
    print(user.model_dump())
    return user


@postDemo.post("/data/")
async def create_data(data: Data):
    return data
